<?php
namespace Home\Controller;
use Lib\Api\AgentApi;
use Lib\Api\AgentBelongApi;
use Lib\Api\OrderApi;
use Lib\Api\OrderCommissionApi;
use Lib\Api\OrganizationApi;
use Lib\Api\OrganizationBelongApi;
use Lib\Api\UserApi;
use Lib\Utils\Utils;
use Think\Controller;

class AgentController extends Controller {

    public function index(){
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		 $url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }
        $this->display();
    }

    public function broker() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		 $url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }
        $data = UserApi::getInfoByCondition(array('a.id' => session('user_id')), "left join fs_agent b on b.id = a.agent_id ", "a.mobile_phone, ifnull(b.audit_state, 0) audit_state, b.name");

        if ($data['audit_state'] == 1) {
            // 跳转到经纪人的管理页面
            $left  = "left join fs_user b on b.agent_id = a.id";
            $field = "a.id, a.balance, a.settlement_money, b.code, b.photo_url";
            $agent = AgentApi::getInfo(array("b.id"=>session("user_id")), $left, $field);

            // count(c.id) as user_num, (select count(id) from fs_order where user_id = c.id and state != 0) as order_num
            // left join fs_user c on c.recommend_id = a.id

            $agent["user_num"] = UserApi::getTotal(array("recommend_id"=>$agent["id"]));

            $agent["order_num"] = OrderApi::getTotal(array("b.recommend_id"=>$agent["id"], array("a.state"=>array("neq", 0))), "left join fs_user b on b.id = a.user_id");

            $this->assign('agent', $agent);
            $this->display("index");
            exit;
        }

        $this->assign('user', $data);
        $this->display();
    }

    public function subApplyBroker() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$arr['url'] = isLogin();
        if ($arr['url'] != false) {
            $this->ajaxReturn($arr);
            exit;
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $relName = $_POST['relName'];
        $user_id = session("user_id");
        $audit_state = $_POST['audit_state'];
        if ($audit_state == 0) {
            // $orgcode = '000008888';
            if (!empty(session("organization_code"))) {
                $orgcode = session("organization_code");
            } else {
                $data['success'] = 0;
                $data['msg'] = '申请失败';
                $this->ajaxReturn($data);
                exit;
            }
            if (!empty($_POST['orgcode'])) {
                $orgcode = $_POST['orgcode'];
            }
            $organization_id = 0;
            $organization_level = 0;
            // 获取机构信息
            $where['_string'] = "concat(p_code,level,code)='".$orgcode."'";
            $organization = OrganizationApi::getInfo($where, "a.id, a.level, b.id as customer_id");
            if (!empty($organization) && !empty($organization['customer_id'])) {
                $organization_id = $organization['id'];
                $organization_level = $organization['level'];
            } else {
                $data['success'] = 0;
                $data['msg'] = '机构编码错误';
                $this->ajaxReturn($data);
                exit;
            }

            $user = UserApi::getInfo(array('id'=>$user_id));
            $agent = AgentApi::getInfo(array("a.mobile_phone"=>$user['mobile_phone'], "b.organization_id"=>$organization_id), "left join fs_agent_belong b on b.agent_id = a.id");
            if (!empty($agent)) {
                $data['success'] = 0;
                $data['msg'] = '请不要重复提交经纪人申请';
                $this->ajaxReturn($data);
                exit;
            }

            $level = 4;
            $AGENTCONFIG = C('AGENTCONFIG');
            for ($i=0; $i<count($AGENTCONFIG); $i++) {
                if ($AGENTCONFIG[$i]['type'] == 'jjr') {
                    $level = $i;
                }
            }

            // 添加账户
            $agent['name'] = $relName;
            $agent['level'] = $level;
            $agent['mobile_phone'] = $user['mobile_phone'];
            $agent['settlement_money'] = 0;
            $agent['balance'] = 0;
            $agent['state'] = 1;
            $agent['audit_state'] = 2;
            $agent['datetime'] = date('Y-m-d H:i:s');
            $agent_id = AgentApi::add($agent);

            if ($agent_id > 0) {
                // 添加经纪人归属
                if ($organization_id > 0) {
                    $user_belong_arr = array();
                    $organization_belong_list = OrganizationBelongApi::getAllList(array("organization_id"=>$organization_id));
                    if (count($organization_belong_list) > 0) {
                        for ($i=0; $i<count($organization_belong_list); $i++) {
                            $user_belong['agent_id'] = $agent_id;
                            $user_belong['organization_id'] = $organization_belong_list[$i]['belong_organization_id'];
                            $user_belong['organization_level'] = $organization_belong_list[$i]['belong_organization_level'];
                            $user_belong['state'] = 1;
                            $user_belong['datetime'] = date('Y-m-d H:i:s');
                            array_push($user_belong_arr, $user_belong);
                        }
                    }

                    $user_belong['agent_id'] = $agent_id;
                    $user_belong['organization_id'] = $organization_id;
                    $user_belong['organization_level'] = $organization_level;
                    $user_belong['state'] = 1;
                    $user_belong['datetime'] = date('Y-m-d H:i:s');
                    array_push($user_belong_arr, $user_belong);
                    if (count($user_belong_arr) > 0) {
                        AgentBelongApi::addAll($user_belong_arr);
                    }
                }

                $user['agent_id'] = $agent_id;
                UserApi::save($user);
                $rel['msg'] = '申请已提交，请耐心等待审核';
            } else {
                $rel['msg'] = '申请提交失败';
            }
        } else {
            $agent = AgentApi::getInfo(array('b.id'=> $user_id), 'left join fs_user b on b.agent_id = a.id', "a.*");
            $agent['audit_state'] = 2;
            AgentApi::save($agent);
            $rel['msg'] = '申请已重新提交，请耐心等待审核';
        }
        $this->ajaxReturn($rel);
    }

    public function users() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		 $url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $totals = UserApi::getTotalByCondition(array("c.id"=>session("user_id")), "left join fs_agent b on b.id = a.recommend_id left join fs_user c on c.agent_id = b.id");
        $this->assign('totals', $totals);
        $this->display();
    }

    public function userList() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$arr['url'] = isLogin();
        if ($arr['url'] != false) {
            $this->ajaxReturn($arr);
            exit;
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $pageNo = $_POST['page'];
        $pageSize = $_POST['pageSize'];
        $mobile_phone = $_POST['mobile_phone'];
        $user_id = session('user_id');

        $map['c.id'] = $user_id;
        if(!empty($mobile_phone)) {
            $map['a.mobile_phone'] = array('like','%'.$mobile_phone.'%');
        }

        $left = "left join fs_agent b on b.id = a.recommend_id left join fs_user c on c.agent_id = b.id";
        $users = UserApi::getList($map, $left, $pageNo, $pageSize, $field = "a.nick_name,a.mobile_phone,a.balance,a.datetime", "datetime desc");
        $totals = UserApi::getTotalByCondition($map, $left);

        if (!empty($users)) {
            for ($i=0; $i>count($users); $i++) {
                $users[$i]["nick_name"] = Utils::userTextDecode($users[$i]["nick_name"]);
            }
        }


        $return_list['totals'] = $totals;
        $return_list["data"] = $users;
        $return_list["success"] = 1;
        $this->ajaxReturn($return_list);
    }

    public function bills() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $map['b.id'] = session('user_id');
        $left = "left join fs_user b on b.agent_id = a.id";
        $left .= " left join fs_agent_settlement c on c.agent_id = a.id";
        $settlement_money = AgentApi::getSum($map,"c.settlement_money", $left);
        $this->assign('settlement_money', $settlement_money);

        $this->assign('begin_date', date("Y-m-d",strtotime("-3 months")).' 00:00');
        $this->assign('end_date', date("Y-m-d").' 23:59');
        $this->display();
    }

    public function order_list() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$arr['url'] = isLogin();
        if ($arr['url'] != false) {
            $this->ajaxReturn($arr);
            exit;
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $pageNo = $_POST['page'];
        $pageSize = $_POST['pageSize'];

        $begin_date = $_POST['begin_date'];
        $end_date = $_POST['end_date'];

        if (!empty($begin_date) && !empty($end_date)) {
            $where['DATE_FORMAT(b.end_time, "%Y-%m-%d")'] = array(array('egt', $begin_date), array('elt',$end_date));
        }

        $left  = "left join fs_user b on b.agent_id = a.id";
        $field = "a.id";
        $agent = AgentApi::getInfo(array("b.id"=>session("user_id")), $left, $field);

        $map["b.agent_id"] = $agent["id"];
        $map["a.state"] = 1;
        // $left = "left join fs_order b on b.id = a.order_id left join fs_user c on c.id = b.user_id left join fs_user d on d.id = c.recommend_id";

        /*$left = "left join fs_order b on b.id = a.order_id";
        $left .= " left join fs_user c on c.id = b.user_id";
        $left .= " left join fs_agent d on d.id = c.recommend_id";
        $left .= " left join fs_user e on e.agent_id = e.id";*/

        $left = "left join fs_user b on b.agent_id = a.agent_id";
        $left .= " left join fs_order c on c.id = a.order_id";
        $left .= " left join fs_user d on d.id = c.user_id";

        $field = "d.nick_name, c.play_name, c.end_time, ifnull(a.commission_money,0) as commission_money";

        $return_list["data"] = OrderCommissionApi::getListByCondition($map, $left, $pageNo, $pageSize, $field, "", "c.end_time desc");

        $return_list["totals"] = OrderCommissionApi::getTotalByCondition($map, $left);
        $return_list["success"] = 1;
        $this->ajaxReturn($return_list);
    }
	
	public function withdrawals() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
		$url = isLogin();
        if ($url != false) {
            header("Location:".$url);
        }
		
        if (empty(session('user_id'))) {
            $rel_url = "../index";
            redirect($rel_url);
            exit;
        }

        $data = AgentApi::getInfo(array("b.id"=>session("user_id")),"left join fs_user b on b.agent_id = a.id","REPLACE(b.mobile_phone, SUBSTR(b.mobile_phone,4,4), '****') as mobile_phone, a.balance, b.photo_url, a.name as nick_name");
        $this->assign('user', $data);

        $modelObj = M("UserBank");
        $userBank_list = $modelObj->where(array('user_id'=>session('user_id')))->select();
        $userBank = array();
        if (!empty($userBank_list)) {
            $userBank = $userBank_list[0];
        }
        $this->assign('userBank', $userBank);

        $modelObj = M("Sys");
        $data = $modelObj->field("lowest_money, highest_money, max_extract_count")->where(array('id' => 1))->find();
        $this->assign('sys', $data);

        $this->assign('source', 2);

        $this->display("user/withdrawals");
    }
}